<template>
  <div>
    <!-- 面包屑导航栏 start -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item class="index" :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>自行车租赁</el-breadcrumb-item>
      <el-breadcrumb-item>自行车列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航栏 end -->
    <!-- 卡片主体区 start -->
    <el-card>
      <!-- 顶部内容 start -->
      <el-row :gutter="20">
        <!-- 搜索重置 start -->
        <!-- <el-col :span="6">
          <el-input placeholder="请输入搜索内容" v-model.trim="queryBackListObj.price" @change="keyDwon" clearable>
            <el-button slot="append" icon="el-icon-search" title="点击搜索" @click="getBackList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button class="btn-reset" @click="restInput($event)">重置</el-button>
        </el-col> -->
        <!-- 搜索重置 end -->
        <!-- 添加 租赁 申报故障 start -->
        <el-col :span="2">
          <el-button class="btn-often" icon="el-icon-plus" @click="addBack($event)" v-show="role">添加</el-button>
        </el-col>
        <el-col :span="2">
          <el-button class="btn-often btn-lease" @click="leaseBack($event)" v-show="!role">租赁</el-button>
        </el-col>
        <el-col :span="2" :offset="9">
          <el-button class="fault btn-fault btn-often" @click="declareFailure($event)" v-show="!role">申报故障</el-button>
        </el-col>
        <!-- 添加 租赁 申报故障 end -->
      </el-row>
      <!-- 表格信息 start -->
      <el-table class="table-back" :data="backList" ref="tabListData" stripe style="width: 100%; min-height: 380px" max-height="420px" @selection-change="checkBoxChange" border>
        <el-table-column type="selection"> </el-table-column>
        <el-table-column type="index" label="序号" width="60"> </el-table-column>
        <el-table-column prop="price" label="价格"> </el-table-column>
        <el-table-column prop="vipPrice" label="会员价" v-if="!role"> </el-table-column>
        <el-table-column prop="createtime" label="创建时间" width="170" sortable> </el-table-column>
        <el-table-column prop="createby" label="创建人"> </el-table-column>
        <el-table-column label="是否可租赁">
          <!-- 作用域插槽:状态图标 -->
          <template slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.isrent === 0"></i>
            <i class="el-icon-error" v-else></i>
          </template>
        </el-table-column>
        <el-table-column label="是否上架" v-show="role" v-if="role">
          <!-- 作用域插槽:状态开关 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isput" active-color="#9acc99" inactive-color="#dcdfe6" @change="switchChange(scope.row)" :disabled="scope.row.isdelete === 1"> </el-switch>
          </template>
        </el-table-column>
        <!-- 作用域插槽:删除标识 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.isdelete === 0">未删除</el-tag>
            <el-tag type="danger" v-else>已删除</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handle" label="操作" fixed="right" v-if="role">
          <template slot-scope="scope">
            <el-button type="text" class="btn-text" @click="editBack($event, scope.row)" :disabled="scope.row.isdelete === 1">修改</el-button>
            <el-button type="text" class="btn-text" @click="deleteBack($event, scope.row.id, scope.row.isput, scope.row.isrent)" :disabled="scope.row.isdelete === 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格信息 end -->
      <!-- 分页信息 start -->
      <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="queryBackListObj.pagenum" :page-sizes="[2, 5, 10, 20]" :page-size="queryBackListObj.pagesize" layout="sizes, prev, pager, next, jumper,total" :total="total"> </el-pagination>
      <!-- 分页信息 end -->
    </el-card>
    <!-- 卡片主体区 end -->

    <!-- 添加租赁自行车弹窗 start -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="resetFormInput">
      <!-- 添加自行车表单 start -->
      <el-form ref="addBackRef" addBackRef class="add-form" label-width="80px" :model="addForm" :rules="addRules">
        <el-form-item label="价格" prop="price">
          <el-input v-model="addForm.price" placeholder="请输入价格" clearable>
            <template slot="append">元/次</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="isput">
          <el-radio-group v-model="addForm.isput">
            <el-radio label="上架">上架</el-radio>
            <el-radio label="下架">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 添加自行车表单 end -->
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-reset" @click="cancel" size="small">取消</el-button>
        <el-button class="btn-reset" @click="resetFormInput" size="small">重置</el-button>
        <el-button class="btn-often" type="primary" @click="saveAddBack" size="small">确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加租赁自行车弹窗 end -->
    <!-- 申报故障弹窗 start -->
    <el-dialog title="申报故障" :visible.sync="declareFailureVisible" @close="resetFailurInput">
      <!-- 申报故障表单 start -->
      <el-form ref="declareFailureRef" declareFailureRef class="add-form" label-width="80px" :model="declareFailurForm" :rules="addRules">
        <el-form-item label="故障描述" prop="textarea">
          <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="declareFailurForm.textarea" clearable> </el-input>
        </el-form-item>
      </el-form>
      <!-- 申报故障表单 end -->
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-reset" @click="cancelFailur" size="small">取消</el-button>
        <el-button class="btn-reset" @click="resetFailurInput" size="small">重置</el-button>
        <el-button class="btn-often" type="primary" @click="saveFailur($event)" size="small">确定</el-button>
      </div>
    </el-dialog>
    <!-- 申报故障弹窗 end -->
  </div>
</template>

<script>
// 引入自定义js文件
import btn from '../utils/btn.js'
import _ from 'lodash'
export default {
  data() {
    // 校验真实姓名(中文或英文)
    const checkPrice = (rule, val, callback) => {
      const reg = /^([1-9]+|0)(.\d{1,2})?$/
      if (!val) {
        return callback(new Error('请输入价格！'))
      } else if (!reg.test(val)) {
        return callback(new Error('请输入数字，最多保留两位小数！'))
      } else {
        return callback()
      }
    }
    return {
      // 表单数据绑定
      addForm: {
        price: '',
        isput: '上架'
      },
      // 表单验证规则绑定
      addRules: {
        // 价格不能为空
        price: [{ validator: checkPrice, required: true, triggger: 'blur' }],
        // 状态不能为空
        isput: [{ required: true, message: '状态不能为空', triggger: 'blur' }],
        textarea: [{ required: true, message: '故障内容不能为空', triggger: 'blur' }]
      },
      // 自行车列表请求参数
      queryBackListObj: {
        price: '',
        pagesize: 5,
        // 当前页
        pagenum: 1
      },
      //   列表信息
      backList: [],
      total: 0,
      //   勾选集合存储
      selectList: [],
      // 添加自行车弹窗
      dialogFormVisible: false,
      openType: '',
      dialogTitle: '',
      // 申报故障弹窗
      declareFailureVisible: false,
      declareFailurForm: {
        textarea: ''
      },
      // true为管理员
      role: false,
      // 具体角色
      userRole: '',
      // 登录用户信息
      user: {}
    }
  },
  created() {
    // 获取角色
    this.getRole()
  },
  watch: {
    // 添加自行车弹窗关闭
    // dialogFormVisible: {
    //   immediate: false,
    //   handler(newVal, oldVal) {
    //     if (!newVal) {
    //       this.resetFormInput()
    //     }
    //   },
    //   deep: true
    // }
  },
  methods: {
    getRole() {
      const user = JSON.parse(window.sessionStorage.getItem('user'))
      this.userRole = user.role
      // 存储登录信息
      this.user = user
      if (user.role === '超级管理员' || user.role === '管理员') {
        // 初始所有自行车列表
        this.getBackList()
        this.role = true
      } else {
        // 获取可租赁车辆信息
        this.getUsedBack()
      }
    },
    // 重置添加自行车表单
    resetFormInput() {
      this.$refs.addBackRef.resetFields()
    },
    // 重置申报故障表单
    resetFailurInput() {
      this.$refs.declareFailureRef.resetFields()
    },
    //   获取所有自行车列表
    async getBackList() {
      const res = await this.$http.get('getBack', {
        params: {
          pageSize: this.queryBackListObj.pagesize,
          pageNum: this.queryBackListObj.pagenum
        }
      })
      //   console.log('查询结果', res)
      if (!res.data) {
        this.$message.error('获取自行车列表失败，请重新操作！')
      } else {
        //   数据赋值
        this.backList = res.data
        this.backList.forEach((item) => {
          item.price = item.price.toFixed(2)
          item.isput = item.isput === 1
        })
        this.pagenum = res.data.pageNum
        // 获取所有车辆信息
        const list = await this.$http.post('getAllBack', {})
        this.total = list.data.length
        // console.log('列表信息', this.backList)
      }
    },
    async getUsedBack() {
      const res = await this.$http.get('getUsedBack', {
        params: {
          pageSize: this.queryBackListObj.pagesize,
          pageNum: this.queryBackListObj.pagenum
        }
      })
      //   console.log('查询结果', res)
      if (!res.data) {
        this.$message.error('获取自行车列表失败，请重新操作！')
      } else {
        //   数据赋值
        this.backList = res.data
        this.backList.forEach((item) => {
          item.price = item.price.toFixed(2)
          item.isput = item.isput === 1
          // 设置会员价
          if (this.userRole === '普通会员') {
            item.vipPrice = (item.price * 0.99).toFixed(2)
          } else if (this.userRole === '高级会员') {
            item.vipPrice = (item.price * 0.9).toFixed(2)
          } else if (this.userRole === '超级会员') {
            item.vipPrice = (item.price * 0.8).toFixed(2)
          } else {
            item.vipPrice = item.price
          }
        })
        this.pagenum = res.data.pageNum
        // 获取所有车辆信息
        const list = await this.$http.post('getAllUsedBack', {})
        this.total = list.data.length
        // console.log('列表信息', this.backList)
      }
    },
    // 重置
    restInput(e) {
      this.queryBackListObj.price = ''
      // 刷新表格数据
      this.getBackList()
      btn.preBtnFocus(e)
    },
    // 表格勾选事件
    checkBoxChange(selectList) {
      if (selectList.length > 0) {
        this.selectList = selectList
      } else {
        this.selectList = []
      }
    },
    // 租赁车子
    async leaseBack(e) {
      btn.preBtnFocus(e)
      // 判断是否勾选
      if (this.selectList.length === 0) {
        this.$message.warning('请至少选中一条自行车进行租赁操作!')
      } else if (this.selectList.length > 1) {
        this.$message.warning('只能选中一条自行车进行租赁操作!')
      } else if (this.selectList.length === 1) {
        if (this.selectList[0].isrent === 1) {
          this.$message.warning('该车辆已被租赁，请选择其他车辆租赁！')
        } else if (this.selectList[0].isdelete === 1) {
          this.$message.warning('该车辆已被报销，请选择其他车辆租赁！')
        } else if (!this.selectList[0].isput) {
          this.$message.warning('该车辆已下架，请选择其他车辆租赁！')
        } else {
          // 调用接口 进行租车操作
          const res = await this.$http.get('updateRent', {
            params: {
              id: this.selectList[0].id,
              isrent: 1,
              uid: this.user.id,
              uname: this.user.uname,
              price: this.selectList[0].vipPrice
            }
          })
          if (res.data === '租车成功！') {
            this.$message.success('租车成功！可以前往订单界面查看租车信息!')
            // 刷新表格数据
            this.getUsedBack()
          } else {
            this.$message.error('租车失败，请刷新后重新租赁')
          }
        }
      }
    },
    // 状态开关值改变
    async switchChange(row) {
      //   console.log('status', status)
      if (row.isrent === 1) {
        this.$message.warning('请等该车完成租赁后下架！')
        row.isput = !row.isput
      } else {
        const data = _.cloneDeep(row)
        data.isput = data.isput ? 1 : 0
        console.log('data', data)
        // 调用接口 修改状态
        const res = await this.$http.get('updatePut', {
          params: {
            id: data.id,
            isput: data.isput
          }
        })
        if (res.data === '修改上架下架状态成功！') {
          if (row.isput) {
            this.$message.success('上架成功!')
          } else {
            this.$message.success('下架成功!')
          }
        } else {
          this.$message.error('操作失败，请刷新后重新操作！')
        }
      }
    },
    // 输入框回车事件
    keyDwon() {
      this.getBackList()
    },
    // 申报故障
    declareFailure(e) {
      btn.preBtnFocus(e)
      this.declareFailureVisible = true
    },
    // 监听pagesize改变事件
    pageSizeChange(pageSize) {
      this.queryBackListObj.pagesize = pageSize
      // 重新分页查询
      if (this.role) {
        this.getBackList()
      } else {
        this.getUsedBack()
      }
    },
    // 监听当前页改变事件
    pageCurrentChange(pageNum) {
      this.queryBackListObj.pagenum = pageNum
      // 重新分页查询
      if (this.role) {
        this.getBackList()
      } else {
        this.getUsedBack()
      }
    },
    // 添加自行车
    addBack(e) {
      btn.preBtnFocus(e)
      this.openType = 'add'
      this.dialogTitle = '添加自行车'
      this.dialogFormVisible = true
    },
    async editBack(e, row) {
      btn.preBtnFocus(e)
      this.openType = 'edit'
      this.rowId = row.id
      this.dialogTitle = '修改自行车信息'
      this.dialogFormVisible = true
      this.addForm.price = row.price
      this.addForm.isput = row.isput === 1 ? '上架' : '下架'
    },
    // 添加、修改自行车
    saveAddBack() {
      this.$refs.addBackRef.validate(async (valid) => {
        if (valid) {
          const data = {
            isput: this.addForm.isput === '上架' ? 1 : 0,
            price: this.addForm.price
          }
          if (this.openType === 'add') {
            data.createby = this.user.uname
            const res = await this.$http.post('addBack', data)
            if (res.data === '添加成功！') {
              this.$message.success('添加成功！')
              this.dialogFormVisible = false
              this.getBackList()
            } else {
              this.$message.error('添加失败，请重新操作！')
            }
          } else if (this.openType === 'edit') {
            // 编辑
            data.id = this.rowId
            const res = await this.$http.post('editBack', data)
            if (res.data === '修改成功！') {
              this.$message.success('修改成功！')
              this.dialogFormVisible = false
              this.getBackList()
            } else {
              this.$message.error('修改失败,请重新操作！')
            }
          }
        }
      })
    },
    // 添加故障申请
    saveFailur(e) {
      btn.preBtnFocus(e)
      this.$refs.declareFailureRef.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post('addFault', {
            uid: this.user.id,
            uname: this.user.uname,
            descs: this.declareFailurForm.textarea
          })
          if (res.data === '添加故障信息成功！') {
            this.$message.success('申报成功！')
            this.declareFailureVisible = false
          } else {
            this.$message.error('申报失败，请重新操作！')
          }
        } else {
          return false
        }
      })
    },
    // 删除自行车
    async deleteBack(e, id, isput, isrent) {
      btn.preBtnFocus(e)

      if (isput) {
        this.$message.warning('请先将该车下架，才可以删除!')
      } else if (isrent === 1) {
        this.$message.warning('请等该车完成租赁，才可以删除!')
      } else {
        const result = await this.$confirm('你确定要删除该用户吗？删除后无法恢复！', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((error) => error)
        // console.log('结果', result)
        if (result !== 'confirm') {
          this.$message.info('已取消删除操作！')
        } else {
          // 删除
          const res = await this.$http.delete('deleteBack', {
            params: {
              id: id
            }
          })
          if (res.data === '删除成功！') {
            this.$message.success('删除成功！')
            this.getBackList()
          } else {
            this.$message.error('删除失败，请重新操作！')
          }
        }
      }
    },
    // 关闭弹窗
    cancel() {
      this.dialogFormVisible = false
      this.$refs.addBackRef.resetFields()
    },
    cancelFailur() {
      this.declareFailureVisible = false
      this.$refs.declareFailureRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
// 表格
.el-col-offset-9 {
  margin-left: 39.7% !important;
}
// 按钮
.btn-lease {
  margin-left: 0px;
}
// 图标
.el-icon-success {
  color: #9acc99;
}
.el-icon-error {
  color: red;
}
i {
  font-size: 20px;
}

// 申报故障按钮
.fault {
  margin-left: 456px;
}
</style>
